package v3

import (
	"bytes"
	"context"
	"crypto/rsa"
	"fmt"
	"github.com/go-pay/gopay"
	"github.com/go-pay/gopay/pkg/xpem"
	"github.com/go-pay/gopay/pkg/xrsa"
	"net/http"
	"time"
)

type ClientV3 struct {
	AppId           string
	AppCertSN       string
	PrivateKey      *rsa.PrivateKey
	AliPayPublicKey string
	Charset         string
	SignType        string
	Format          string
}

func NewClientV3(appid, privateKey, alipayPublicKey string) (client *ClientV3, err error) {
	key := xrsa.FormatAlipayPrivateKey(privateKey)
	priKey, err := xpem.DecodePrivateKey([]byte(key))

	if err != nil {
		return nil, err
	}
	client = &ClientV3{
		AppId:           appid,
		Charset:         UTF8,
		PrivateKey:      priKey,
		AliPayPublicKey: alipayPublicKey,
		SignType:        "RSA2",
		Format:          "json",
	}

	return client, nil
}

func (c *ClientV3) Post(url string, headers map[string]string, bm gopay.BodyMap) (*PayData, http.Header, error) {
	//headers["ws_service_url"] = "iotmbs-380.gz00b.dev.alipay.net:12200"
	bm.Set("app_id", c.AppId)
	bm.Set("format", "json")
	bm.Set("charset", c.Charset)
	bm.Set("sign_type", c.SignType)
	bm.Set("private_key", c.PrivateKey)
	req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader([]byte(bm.JsonBody())))
	if err != nil {
		return nil, nil, err
	}
	for h, v := range headers {
		req.Header.Set(h, v)
	}
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	req = req.WithContext(ctx)

	httpClient := &http.Client{}
	httpResp, err := httpClient.Do(req) // 发送HTTP请求并返回HTTP响应
	if err != nil {
		return nil, nil, err
	}
	defer httpResp.Body.Close()
	headerResp := httpResp.Header.Clone()
	respData := NewPayData()
	err = respData.FromJson(httpResp.Body)
	if err != nil {
		return nil, nil, err
	}
	if httpResp.StatusCode != http.StatusOK {
		return respData, headerResp, fmt.Errorf("http.Status: %s", httpResp.Status)
	}
	return respData, headerResp, nil
}

func (c *ClientV3) Get() {

}
